<template>
  <div class="wrap-container">
    <div class="search_box">
      <div class="manage_tit mb-4">
        <div class="line"></div>
        <p>优惠券筛选</p>
      </div>
      <el-form :inline="true" label-position="left" label-width="76px">
        <el-form-item label="优惠券名称">
          <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="优惠券编码">
          <el-input v-model="queryParams.code" placeholder="请输入优惠券编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select filterable clearable v-model="queryParams.type" placeholder="请选择优惠券类型">
            <el-option
              v-for="dict in dict?.type?.coupon_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="适用场馆">
          <el-select
            v-model="queryParams.stadiumId"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="请输入场馆名"
            :remote-method="handleQueryStadium"
            :loading="loading"
          >
            <el-option
              v-for="item in stadiumOptions"
              :key="item.id"
              :label="item.stadiumName"
              :value="item.id"
            >
              <span style="float: left">{{ item.stadiumName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.stadiumName
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用类型">
          <el-select
            filterable
            clearable
            v-model="queryParams.siteType"
            placeholder="请选择适用类型"
          >
            <el-option
              v-for="dict in dict?.type?.site_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="领取方式">
          <el-select
            filterable
            clearable
            v-model="queryParams.limitType"
            placeholder="请选择领取方式"
          >
            <el-option
              v-for="dict in limitTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布渠道">
          <el-select filterable clearable v-model="queryParams.sourceType" placeholder="请选择">
            <el-option
              v-for="dict in dict?.type?.platform_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            type="daterange"
            range-separator="至"
            start-placeholder="-年-月-日"
            end-placeholder="-年-月-日"
            v-model="dateArr"
            value-format="yyyy-MM-dd"
            @change="changeDateRange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item class="search_btn">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box">
      <div class="tabs_box">
        <el-tabs v-model="tabsVal" @tab-change="handleClick">
          <el-tab-pane
            :label="`${item.name} (${item.num})`"
            :name="item.id"
            v-for="item in tabsList"
            :key="item.id"
          ></el-tab-pane>
        </el-tabs>
        <el-button
          type="primary"
          class="save_btn"
          @click="handleAdd"
          v-hasPermi="['sys:coupons:btn_add']"
          >新增优惠券
        </el-button>
        <el-button
          type="info"
          class="del_btn"
          @click="handleBatchDelete"
          v-hasPermi="['sys:coupons:btn_batch_del']"
          >批量删除
        </el-button>
      </div>
      <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          label="优惠券编码"
          prop="code"
          show-overflow-tooltip
          width="120"
        ></el-table-column>
        <el-table-column
          label="优惠券名称"
          prop="name"
          width="140"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="优惠券类型" width="90" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-for="item in dict?.type?.coupon_type" :key="item.value">
              <div v-if="item.value == String(row.type)">
                {{ item.label }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="使用条件" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.type === 3">满{{ row.thresholdAmount }}减{{ row.faceValue }}</div>
            <div v-else-if="row.type == 2">抵扣{{ row.freeHours }}小时</div>
            <!-- <div
              v-else-if="
                row.type === 2 && row.discountType === 4 && row.cardType === 1
              "
            >
              次卡
            </div>
            <div
              v-else-if="
                row.type === 2 && row.discountType === 4 && row.cardType === 2
              "
            >
              周卡
            </div>
            <div
              v-else-if="
                row.type === 2 && row.discountType === 4 && row.cardType === 3
              "
            >
              月卡
            </div> -->
            <div v-else>无门槛</div>
          </template>
        </el-table-column>
        <el-table-column label="适用场馆" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.applyStadiumType === null">--</div>
            <div v-else-if="row.applyStadiumType === 1">全部场馆</div>
            <div v-else>指定场馆</div>
          </template>
        </el-table-column>
        <el-table-column label="适用类型" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.applySportType === null">--</div>
            <div v-else-if="row.applySportType === 1">全部类型</div>
            <div v-else>指定类型</div>
          </template>
        </el-table-column>
        <el-table-column label="领取方式" width="90" show-overflow-tooltip>
          <template #default="{ row }">
            <template v-if="row.limitType == null">--</template>
            <template v-else>
              <div v-for="item in limitTypeOptions" :key="item.value">
                <div v-if="item.value == row.limitType">
                  {{ item.label }}
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="状态" show-overflow-tooltip width="80">
          <template #default="{ row }">
            <div v-if="row.enable === 1" style="color: rgba(42, 130, 228, 1)">启用</div>
            <div v-else-if="row.enable === 0" style="color: #f56c6c">停用</div>
          </template>
        </el-table-column>
        <el-table-column label="发布渠道" show-overflow-tooltip width="80">
          <template #default="{ row }">
            <div v-for="item in dict?.type?.platform_type" :key="item.value">
              <div v-if="item.value == String(row.sourceType)">
                {{ item.label }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有效期" show-overflow-tooltip width="150">
          <template #default="{ row }">
            <div v-if="row.lifespanType === 1">
              {{ row.lifespanDay == 0 ? '--' : `领券当日${row.lifespanDay}天有效` }}
            </div>
            <div v-else-if="row.lifespanType === 2" class="leading-5">
              {{ row.lifespanStartTime }}
              <p class="text-center">至</p>
              {{ row.lifespanEndTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="发放总量"
          prop="total"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="领取人数"
          prop="userReceiveTotal"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="使用人数"
          prop="userUseTotal"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <div class="table_btn">
              <el-button
                type="text"
                class="primary_text"
                @click="handleUpdate(row.id)"
                :disabled="row.enable === 0"
                >编辑
              </el-button>
              <span class="line"></span>
              <el-dropdown @command="(command) => handleCommand(command, row)">
                <el-button type="text" class="primary_text">
                  更多
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      command="handleBatchSend"
                      v-hasPermi="['sys:coupons:btn_copy']"
                      :disabled="
                        row.enable === 0 ||
                        (row.conditionAudit != null &&
                          (row.conditionAudit == 0 || row.conditionAudit == 1))
                      "
                      >发布
                    </el-dropdown-item>
                    <el-dropdown-item command="handleCopy" v-hasPermi="['sys:coupons:btn_copy']"
                      >复制
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleCheckSend"
                      v-hasPermi="['sys:coupons:send_view']"
                      >查看发放</el-dropdown-item
                    >
                    <el-dropdown-item
                      command="handleEnable"
                      v-if="row.enable == 1"
                      v-hasPermi="['sys:coupons:enable']"
                      >停用</el-dropdown-item
                    >
                    <el-dropdown-item
                      command="handleEnableStop"
                      v-hasPermi="['sys:coupons:enable']"
                      v-if="row.enable == 0"
                      >启用</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 查看发放 -->
    <check-coupons-send
      v-if="checkCouponsSend"
      ref="checkCouponsSendRef"
      @refreshShow="handleRefreshShow"
    ></check-coupons-send>

    <!-- 查看卡券发放 -->
    <check-card-send v-if="checkCardSend" ref="checkCardSendRef" @refreshShow="handleRefreshShow">
    </check-card-send>
    <!-- 批量发放 -->
    <batch-send
      v-if="batchSend"
      :type="'0'"
      ref="batchSendRef"
      @refreshShow="handleRefreshShow"
    ></batch-send>

    <!--生成二维码-->
    <generate-qr-code
      v-if="generateQrCode"
      ref="generateQrCodeRef"
      @refreshShow="handleRefreshShow"
    >
    </generate-qr-code>
    <!-- 生成兑换码 -->
    <exchange-setting v-if="exchangeSetting" ref="exchangeSettingRef"></exchange-setting>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pageCoupon, countCoupon, getCoupon, enableCoupon, deleteCoupon } from '@/api/coupon/coupon'
import CheckCouponsSend from './common/checkCouponsSend.vue'
import BatchSend from './common/batchSend.vue'
import { getStadiumInfo } from '@/api/stadium/stadium'
import GenerateQrCode from './common/generateQrCode.vue'
import CheckCardSend from './common/checkCardSend.vue'
import ExchangeSetting from './common/exchangeSetting.vue'

// 字典数据
const { dict } = useDict({
  dicts: ['platform_type', 'coupon_type', 'site_type', 'discount_card_type'],
})

// 定义响应式数据
const router = useRouter()
const total = ref(0)
const stadiumOptions = ref<any[]>([])
const tabsVal = ref('-1')
const loading = ref(false)
const list = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const checkCouponsSend = ref(false)
const batchSend = ref(false)
const generateQrCode = ref(false)
const checkCardSend = ref(false)
const exchangeSetting = ref(false)
const dateArr = ref([])

const tabsList = ref([
  { id: '-1', name: '全部', num: 0 },
  { id: '1', name: '启用', num: 0 },
  { id: '0', name: '停用', num: 0 },
])

const limitTypeOptions = [
  { value: '1', label: '免费领取' },
  { value: '2', label: '指定发放' },
  { value: '3', label: '兑换领取' },
  { value: '4', label: '二维码领取 ' },
  { value: '5', label: '购买领取' },
]

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null as string | null,
  code: null as string | null,
  type: null as string | null,
  stadiumId: null as number | null,
  siteType: null as string | null,
  limitType: null as string | null,
  sourceType: null as string | null,
  lifespanStartTime: null as string | null,
  lifespanEndTime: null as string | null,
  enable: '' as string | number,
})

const checkCouponsSendRef = ref<InstanceType<typeof CheckCouponsSend> | null>(null)
const checkCardSendRef = ref<InstanceType<typeof CheckCardSend> | null>(null)
const batchSendRef = ref<InstanceType<typeof BatchSend> | null>(null)
const generateQrCodeRef = ref<InstanceType<typeof GenerateQrCode> | null>(null)
const exchangeSettingRef = ref<InstanceType<typeof ExchangeSetting> | null>(null)

onMounted(() => {
  getList()
  getCount()
})

const handleQueryStadium = (query: string) => {
  if (query !== '') {
    getStadiumInfo({ stadiumName: query }).then((res: any) => {
      stadiumOptions.value = res.data
    })
  } else {
    stadiumOptions.value = []
  }
}

// 表格tabs切换
const handleClick = () => {
  queryParams.enable = tabsVal.value == '-1' ? '' : tabsVal.value
  queryParams.pageNum = 1
  getList()
}

// 选择有效期
const changeDateRange = (val: any) => {
  if (val != null) {
    queryParams.lifespanStartTime = val[0]
    queryParams.lifespanEndTime = val[1]
  } else {
    queryParams.lifespanStartTime = null
    queryParams.lifespanEndTime = null
  }
}

// 查询
const handleQuery = () => {
  getList()
  getCount()
}

// 重置
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    name: null,
    code: null,
    type: null,
    stadiumId: null,
    siteType: null,
    limitType: null,
    sourceType: null,
    lifespanStartTime: null,
    lifespanEndTime: null,
    enable: '',
  })
  dateArr.value = []
  getList()
  getCount()
}

// 加载数据
const getList = () => {
  console.log(queryParams)
  loading.value = true
  pageCoupon(queryParams)
    .then((res: any) => {
      loading.value = false
      list.value = res.rows
      total.value = res.total
    })
    .catch((e: any) => {
      loading.value = false
    })
}

const getCount = () => {
  countCoupon(queryParams).then((res: any) => {
    tabsList.value[0].num = res.data.countAll
    tabsList.value[1].num = res.data.countQy
    tabsList.value[2].num = res.data.countTy
  })
}

// 表格多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 新增
const handleAdd = () => {
  router.push({ path: '/coupon/addV3', query: { type: '0' } })
}

// 批量发放
const handleBatchSend = (row: any) => {
  batchSend.value = true
  batchSendRef.value?.init(row.id)
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length <= 0) {
    return ElMessage.warning('请选择要删除的数据')
  }
  const ids = multipleSelection.value.map((item) => item.id)
  ElMessageBox.confirm(`确认要删除吗？`)
    .then(() => {
      deleteCoupon(ids).then((res: any) => {
        ElMessage.success(res.msg)
        getList()
        getCount()
      })
    })
    .catch(() => {})
}

// 复制
const handleCopy = (val: any) => {
  ElMessageBox.confirm(`复制该优惠券，并以此为模板创建新的优惠券？`)
    .then(() => {
      getDetail(1, val)
    })
    .catch(() => {})
}

// 获取优惠券详情
const getDetail = (type: number, val: any) => {
  getCoupon(val).then((res: any) => {
    if (type === 1) {
      router.push({
        path: '/coupon/addV3',
        query: { form: JSON.stringify(res.data), type: '0' },
      })
    }
  })
}

// 编辑
const handleUpdate = (val: any) => {
  router.push({ path: '/coupon/updateV3', query: { data: val, type: '0' } })
}

// 查看发放-优惠券
const handleCheckSend = (val: any) => {
  const typeName = dict.value.type.coupon_type.find((item: any) => item.value == val.type).label
  checkCouponsSend.value = true
  checkCouponsSendRef.value?.init(val.id, val.name, typeName)
}

// 刷新
const handleRefreshShow = () => {
  checkCouponsSend.value = false
  batchSend.value = false
  generateQrCode.value = false
  getList()
}

// 启用/停用
const handleEnable = (id: number, enable: number) => {
  const text = enable === 1 ? `启用` : `停用`
  ElMessageBox.confirm(`确认要` + text + `吗？`)
    .then(() => {
      enableCoupon(id).then((res: any) => {
        getList()
        ElMessage.success(res.msg)
      })
    })
    .catch(() => {})
}

// 更多操作触发
const handleCommand = (command: string, row: any) => {
  switch (command) {
    case 'handleBatchSend':
      handleBatchSend(row)
      break
    case 'handleCopy':
      handleCopy(row.id)
      break
    case 'handleCheckSend':
      handleCheckSend(row)
      break
    case 'handleEnable':
      handleEnable(row.id, 0)
      break
    case 'handleEnableStop':
      handleEnable(row.id, 1)
      break
    default:
      break
  }
}

const formatter = (row: any, column: any, cellValue: any) => {
  // 如果单元格值为空或为 null，返回 '--'
  return cellValue || '--'
}
</script>

<style lang="scss" scoped>
.search_box {
  padding-bottom: 0;
}

.table_box {
  padding-top: 15px;

  .handle_btn {
    margin-bottom: 11px;
  }

  .tabs_box {
    position: relative;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 15px;

    :deep(.el-tabs) {
      flex: 1;

      .el-tabs__header {
        margin: 0;
      }
    }

    .bath_btn {
      width: 75px;
      height: 26px;
      line-height: 26px;
      background: rgba(255, 141, 26, 1);
      border-radius: 6px;
      padding: 0;
      color: #fff;
      font-size: 12px;
      margin-left: 63px;
    }

    .save_btn {
      width: 75px;
      height: 26px;
      line-height: 26px;
      background: #2a82e4;
      border-radius: 6px;
      padding: 0;
      color: #fff;
      margin-left: 15px;
      font-size: 12px;
    }

    .del_btn {
      width: 75px;
      height: 26px;
      line-height: 26px;
      background: rgba(255, 255, 255, 1);
      border-radius: 6px;
      padding: 0;
      color: rgba(56, 56, 56, 1);
      margin-left: 15px;
      font-size: 12px;
    }
  }
}
.table_btn {
  display: flex;
  align-items: center;
  .line {
    display: block;
    width: 1px;
    height: 10px;
    background: #a6a6a6;
    margin: 0 5px 0 10px;
  }
}
</style>
